//
//  BluetoothController.m
//  MHTReceipt
//
//  Created by Mac on 2018/11/6.
//  Copyright © 2018年 Mac. All rights reserved.
//

#import "BluetoothController.h"
#import "BluetoothModel.h"
#import "PrinterBluetoothManager.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "BluetoothUITableViewCell.h"

@interface BluetoothController ()

@property (strong,nonatomic) UILabel *navBackUILabel, *bluetoothUILabel;

@property (strong,nonatomic) UITableView *bluetoothDeviceUITableView;

//蓝牙设备数组
@property (strong,nonatomic) NSMutableArray<BluetoothModel *> *bluetoothModels;

//蓝牙管理器
@property (strong,nonatomic) PrinterBluetoothManager *bluetoothManager;

@end

@implementation BluetoothController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    
    self.bluetoothModels = [NSMutableArray arrayWithCapacity:5];
    //获取一个蓝牙管理实例
    self.bluetoothManager = [PrinterBluetoothManager printerBluetoothManagerInstance];
    //初始化蓝牙回调（发送蓝牙设备回调，蓝牙连接成功回调）
    [self initBlock];
    //开始扫描蓝牙
    [self beginScan];
    
}

- (void)viewDidDisappear:(BOOL)animated{
    [self.bluetoothManager stopScan];
}

-(void)initBlock{
     __weak typeof(self) weakSelf = self;
    //发现蓝牙设备回调
    [self.bluetoothManager blePeripheralFound:^(CBPeripheral * _Nonnull peripheral, NSNumber* rssi) {
        NSString *uuid = peripheral.identifier.UUIDString;
        for(int i = 0; i < weakSelf.bluetoothModels.count;i++){
            BluetoothModel *bluetoothModel = weakSelf.bluetoothModels[i];
            NSString *tempUUID = bluetoothModel.peripheral.identifier.UUIDString;
            if([uuid isEqualToString:tempUUID]){
                return;
            }
        }
        
        BluetoothModel *bluetoothModel = [[BluetoothModel alloc] init];
        bluetoothModel.peripheral = peripheral;
        bluetoothModel.rssi = rssi;
        [weakSelf.bluetoothModels addObject:bluetoothModel];
        [weakSelf.bluetoothModels sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            return [((BluetoothModel*)obj1).rssi intValue] < [((BluetoothModel*)obj2).rssi intValue];
        }];
        [weakSelf.bluetoothDeviceUITableView reloadData];
    }];
    //蓝牙连接成功回调
    [self.bluetoothManager blePeripheralConnected:^(CBCentralManager * _Nonnull central, CBPeripheral * _Nonnull peripheral) {
        NSLog(@"connect succeeded");
        [weakSelf dismissViewControllerAnimated:true completion:nil];
    }];
}

-(CGFloat)getRectNavAndStatusHight{
    float statusBarHeight = 0;
    if (@available(iOS 13.0, *)) {
        UIStatusBarManager *statusBarManager = [UIApplication sharedApplication].windows.firstObject.windowScene.statusBarManager;
        statusBarHeight = statusBarManager.statusBarFrame.size.height;
    }else {
        statusBarHeight = [UIApplication sharedApplication].statusBarFrame.size.height;
    }
    return statusBarHeight;
}

-(void)initView{
    CGFloat endY = [self getRectNavAndStatusHight];
    self.view.backgroundColor = [UIColor whiteColor];
    endY = [self initBluetoothUILabel:endY];
    endY = [self initBluetoothDeviceUITableView:endY];
}


//开始扫描蓝牙设备
-(void)beginScan{
    [self.bluetoothModels removeAllObjects];
    [self.bluetoothDeviceUITableView reloadData];
    [self.bluetoothManager beginScan];
}


-(CGFloat)initBluetoothDeviceUITableView:(CGFloat)startY{
    self.bluetoothDeviceUITableView = [[UITableView alloc] init];
    self.bluetoothDeviceUITableView.frame = CGRectMake(0, startY, SCREEN_WIDTH, SCREEN_HEIGHT - startY);
    self.bluetoothDeviceUITableView.showsVerticalScrollIndicator = false;
    self.bluetoothDeviceUITableView.showsHorizontalScrollIndicator = false;
    self.bluetoothDeviceUITableView.delegate = self;
    self.bluetoothDeviceUITableView.dataSource = self;
    [self.view addSubview:self.bluetoothDeviceUITableView];
    
    return self.bluetoothDeviceUITableView.frame.origin.y + self.bluetoothDeviceUITableView.frame.size.height;
}

-(CGFloat)initBluetoothUILabel:(CGFloat)startY{
    self.bluetoothUILabel = [[UILabel alloc] init];
    self.bluetoothUILabel.frame = CGRectMake(50, startY, SCREEN_WIDTH - 100, 35);
    self.bluetoothUILabel.text = @"Bluetooth list";
    self.bluetoothUILabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.bluetoothUILabel];
    
    self.navBackUILabel = [[UILabel alloc] init];
    self.navBackUILabel.frame = CGRectMake(5, startY, 50, 35);
    self.navBackUILabel.text = @"Back";
    self.navBackUILabel.font = [UIFont systemFontOfSize:15];
    self.navBackUILabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.navBackUILabel];
    self.navBackUILabel.userInteractionEnabled = YES;
    [self.navBackUILabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backAction:)]];
    
    return self.bluetoothUILabel.frame.origin.y + self.bluetoothUILabel.frame.size.height;
}

-(void)backAction:(UITapGestureRecognizer *)recognizer{
    [self dismissViewControllerAnimated:true completion:NULL];
}

//返回一个cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    int row = (int)indexPath.row;
    
    BluetoothModel *bluetoothModel = self.bluetoothModels[row];
    BluetoothUITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(cell == nil){
        cell = [[BluetoothUITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
        [cell initUIView: CGSizeMake(SCREEN_WIDTH, 50)];
    }
    NSString *name = bluetoothModel.peripheral.name;
    NSString *uuid = bluetoothModel.peripheral.identifier.UUIDString;
    if(bluetoothModel.macAddress != nil && ![bluetoothModel.macAddress isEqualToString:@""]){
        uuid = bluetoothModel.macAddress;
    }
    [cell setData:name withUUID:uuid];
    return cell;
}

//返回cell的数量
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.bluetoothModels.count;
}

//点击蓝牙设备item
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    int row = (int)indexPath.row;
    BluetoothModel *bluetoothModel = self.bluetoothModels[row];
    //连接蓝牙
    [self.bluetoothManager connect:bluetoothModel.peripheral];
}

//返回高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

@end
